"ui";

importClass(android.widget.Toast);
var toast = (function () {
    var singleton;
    function TOAST(msg) {
        var msg = msg.toString();
        singleton && singleton.cancel();
        singleton = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
        singleton.setText(msg);
        singleton.show();
    }
    return TOAST;
})();

toast("感谢您的使用，祝您使用愉快！");

ui.layout(
    <frame>
        <vertical>
            <appbar>
                <toolbar id="toolbar" title="听写记" />
                <tabs id="tabs" />
            </appbar>

            <viewpager id="viewpager">
                <frame>
                    <vertical>
                        <horizontal>
                            <text id="text_test" w="{{device.width/6}}" ellipsize="middle" lines="1" />
                            <button id="awz" hint="选择文件" />
                            <button id="dengru" hint="导入" />
                        </horizontal>
                        <linear gravity="center">
                            <button id="selectAll" text="全选" />
                            <button id="antiselectAll" text="反选" />
                            <button id="deleteselect" text="删除" />
                            <button id="Addtoselect" text="添加" />
                        </linear>
                        <ScrollView>
                            <list id="todoList">
                                <card w="*" h="70" margin="10 5" cardCornerRadius="4dp"
                                    cardElevation="1dp" foreground="?selectableItemBackground">
                                    <horizontal gravity="center_vertical">
                                        <View bg="{{this.color}}" h="*" w="10" />
                                        <vertical padding="10 8" h="auto" w="0" layout_weight="1">
                                            <text id="title" text="{{this.title}}" textColor="#222222" textSize="16sp" maxLines="1" />
                                            <text text="{{this.summary}}" textColor="#999999" textSize="14sp" maxLines="1" />
                                        </vertical>
                                        <checkbox id="done" marginLeft="4" marginRight="6" checked="{{this.done}}" />
                                    </horizontal>

                                </card>
                            </list>
                        </ScrollView>
                    </vertical>
                    <fab id="play" w="auto" h="auto" src="@drawable/ic_play_arrow_black_48dp" margin="16" layout_gravity="bottom|left" tint="#ffffff" />
                    <fab id="stop" w="auto" h="auto" visibility="gone" src="@drawable/ic_stop_black_48dp" margin="16" layout_gravity="bottom|left" tint="#ffffff" />
                    <fab id="add" w="auto" h="auto" src="@drawable/ic_add_black_48dp" margin="16" layout_gravity="bottom|right" tint="#ffffff" />
                </frame>

                <frame>
                    <vertical>
                        <linear gravity="center">
                            <button id="cuotiselectAll" text="全选" />
                            <button id="cuotiantiselectAll" text="反选" />
                            <button id="cuotideleteselect" text="删除" />
                        </linear>
                        <ScrollView>
                            <list id="cuotiList">
                                <card w="*" h="70" margin="10 5" cardCornerRadius="4dp"
                                    cardElevation="1dp" foreground="?selectableItemBackground">
                                    <horizontal gravity="center_vertical">
                                        <View bg="{{this.color}}" h="*" w="10" />
                                        <vertical padding="10 8" h="auto" w="0" layout_weight="1">
                                            <text id="title" text="{{this.title}}" textColor="#222222" textSize="16sp" maxLines="1" />
                                            <text text="{{this.summary}}" textColor="#999999" textSize="14sp" maxLines="1" />
                                        </vertical>
                                        <checkbox id="done" marginLeft="4" marginRight="6" checked="{{this.done}}" />
                                    </horizontal>

                                </card>
                            </list>
                        </ScrollView>
                    </vertical>
                    <fab id="cuotiplay" w="auto" h="auto" src="@drawable/ic_play_arrow_black_48dp" margin="16" layout_gravity="bottom|left" tint="#ffffff" />
                </frame>

            </viewpager>

        </vertical>
    </frame>
);

//设置滑动页面的标题
ui.viewpager.setTitles(["听写页", "错词集"]);
//让滑动页面和标签栏联动
ui.tabs.setupWithViewPager(ui.viewpager);

//创建选项菜单(右上角)
ui.emitter.on("create_options_menu", menu => {
    menu.add("高级设置");
    menu.add("关于软件");
});
//监听选项菜单点击
ui.emitter.on("options_item_selected", (e, item) => {
    switch (item.getTitle()) {
        case "高级设置":
            app.startActivity("settings");
            break;
        case "关于软件":
            alert("关于软件", "当前版本号为：" + app.versionName);
            break;
    }
    e.consumed = true;
});
activity.setSupportActionBar(ui.toolbar);

var materialColors = ["#e91e63", "#ab47bc", "#5c6bc0", "#7e57c2", "##2196f3", "#00bcd4",
    "#26a69a", "#4caf50", "#8bc34a", "#ffeb3b", "#ffa726", "#78909c", "#8d6e63"];

var storage = storages.create("todoList");

//从storage获取todo列表
var todoList = storage.get("items", [
    {
        title: "one",
        summary: "1",
        color: "#f44336",
        done: false
    },
    {
        title: "two",
        summary: "2",
        color: "#ff5722",
        done: false
    },
    {
        title: "three",
        summary: "3",
        color: "#4caf50",
        done: false
    },
]);;

ui.todoList.setDataSource(todoList);

ui.selectAll.on("click", function () {
    if (ui.selectAll.getText() == "全选") {
        todoList.forEach(item => {
            item.done = true;
        });
        ui.run(() => {
            ui.selectAll.setText("全不选");
        });
        // 通知数据全部更新
        ui.todoList.adapter.notifyDataSetChanged();
    } else {
        todoList.forEach(item => {
            item.done = false;
        });
        ui.run(() => {
            ui.selectAll.setText("全选");
        });
        // 通知数据全部更新
        ui.todoList.adapter.notifyDataSetChanged();
    }
});


ui.cuotiselectAll.on("click", function () {
    if (ui.cuotiselectAll.getText() == "全选") {
        cuoti.forEach(item => {
            item.done = true;
        });
        ui.run(() => {
            ui.cuotiselectAll.setText("全不选");
        });
        // 通知数据全部更新
        ui.cuotiList.adapter.notifyDataSetChanged();
    } else {
        cuoti.forEach(item => {
            item.done = false;
        });
        ui.run(() => {
            ui.cuotiselectAll.setText("全选");
        });
        // 通知数据全部更新
        ui.cuotiList.adapter.notifyDataSetChanged();
    }
});


ui.antiselectAll.on("click", function () {
    if (ui.selectAll.getText() == "全不选") {
        ui.run(() => {
            ui.selectAll.setText("全选");
        });
    }
    todoList.forEach(item => {
        if (item.done == true) {
            item.done = false;
        } else {
            item.done = true;
        }
    });
    // 通知数据全部更新
    ui.todoList.adapter.notifyDataSetChanged();
});

ui.cuotiantiselectAll.on("click", function () {
    if (ui.cuotiselectAll.getText() == "全不选") {
        ui.run(() => {
            ui.cuotiselectAll.setText("全选");
        });
    }
    cuoti.forEach(item => {
        if (item.done == true) {
            item.done = false;
        } else {
            item.done = true;
        }
    });
    // 通知数据全部更新
    ui.cuotiList.adapter.notifyDataSetChanged();
});

ui.deleteselect.on("click", function () {
    // var Subscript = 0;
    for (var mark = 0; mark < todoList.length; mark++)
        if (todoList[mark].done == true) {
            todoList.splice(mark, 1);
            mark--;
        }
});

ui.cuotideleteselect.on("click", function () {
    // var Subscript = 0;
    for (var cuotimark = 0; cuotimark < cuoti.length; cuotimark++)
        if (cuoti[cuotimark].done == true) {
            cuoti.splice(cuotimark, 1);
            cuotimark--;
        }
});

var cuoti = [];
ui.Addtoselect.on("click", function () {
    for (var mark = 0; mark < todoList.length; mark++)
        if (todoList[mark].done == true) {
            todoList[mark].done = false;
            cuoti.push(todoList[mark])
        }
    storage.put("cuoti", cuoti);
    ui.cuotiList.setDataSource(cuoti);
    toast("已添加至错词集")
});

ui.todoList.on("item_bind", function (itemView, itemHolder) {
    //绑定勾选框事件
    itemView.done.on("check", function (checked) {
        let item = itemHolder.item;
        item.done = checked;
        let paint = itemView.title.paint;
        //设置或取消中划线效果
        if (checked) {
            paint.flags |= Paint.STRIKE_THRU_TEXT_FLAG;
        } else {
            paint.flags &= ~Paint.STRIKE_THRU_TEXT_FLAG;
        }
        itemView.title.invalidate();
    });
});


ui.cuotiList.on("item_bind", function (itemView, itemHolder) {
    //绑定勾选框事件
    itemView.done.on("check", function (checked) {
        let item = itemHolder.item;
        item.done = checked;
        let paint = itemView.title.paint;
        //设置或取消中划线效果
        if (checked) {
            paint.flags |= Paint.STRIKE_THRU_TEXT_FLAG;
        } else {
            paint.flags &= ~Paint.STRIKE_THRU_TEXT_FLAG;
        }
        itemView.title.invalidate();
    });
});

ui.todoList.on("item_click", function (item, i, itemView, listView) {
    itemView.done.checked = !itemView.done.checked;
});

ui.cuotiList.on("item_click", function (item, i, itemView, listView) {
    itemView.done.checked = !itemView.done.checked;
});

ui.todoList.on("item_long_click", function (e, item, i, itemView, listView) {
    confirm("确定要删除" + item.title + "吗？")
        .then(ok => {
            if (ok) {
                todoList.splice(i, 1);
            }
        });
    e.consumed = true;
});

ui.cuotiList.on("item_long_click", function (e, item, i, itemView, listView) {
    confirm("确定要删除" + item.title + "吗？")
        .then(ok => {
            if (ok) {
                cuoti.splice(i, 1);
            }
        });
    e.consumed = true;
});

//当离开本界面时保存todoList
ui.emitter.on("pause", () => {
    storage.put("items", todoList);
    storage.put("cuoti", cuoti);
});

ui.add.on("click", () => {
    dialogs.rawInput("请输入单词")
        .then(title => {
            if (!title) {
                return;
            }
            dialogs.rawInput("请输入词义")
                .then(summary => {
                    todoList.push({
                        title: title,
                        summary: summary,
                        color: materialColors[random(0, materialColors.length - 1)]
                    });
                });
        })
});

var zhuangtai = 0;
ui.play.on("click", () => {
    ui.run(function () {
        ui.play.setVisibility(8)
        ui.stop.setVisibility(0)
    });
    if (zhuangtai == 0) {
        stopzhuangtai = 1;
        threads.start(extract);
    }
});

var stopzhuangtai = 1;
ui.stop.on("click", () => {
    ui.run(function () {
        ui.play.setVisibility(0)
        ui.stop.setVisibility(8)
    });
    zhuangtai == 0;
    stopzhuangtai = 0;
});

var cuotizhuangtai = 0;
ui.cuotiplay.on("click", () => {
    if (cuotizhuangtai == 0) {
        threads.start(extract);
    }
});

function extract() {
    zhuangtai = 1;
    sleep(5000);
    if (todoList != "" || todoList != undefined) {
        var englishwords = "";
        var totalenglish = 0;
        todoList.forEach(element => {
            englishwords += "." + element.title;
            totalenglish++;
        });
        for (i = 1; i <= totalenglish; i++) {
            var word = englishwords.toString().split('.')[i];
            var yuyin = http.get("http://dict.youdao.com/dictvoice?audio=" + word);
            files.writeBytes("/storage/emulated/0/music.mp3", yuyin.body.bytes());
            if (stopzhuangtai == 1) {
                media.playMusic("/storage/emulated/0/music.mp3");
                sleep(media.getMusicDuration() + 3000);
            }
            if (stopzhuangtai == 1) {
                media.playMusic("/storage/emulated/0/music.mp3");
                sleep(media.getMusicDuration() + 5000);
            }
        }
    }
    stopzhuangtai = 1;
    zhuangtai = 0;
}


function cuotiextract() {
    cuotizhuangtai = 1;
    if (cuoti != "" || cuoti != undefined) {
        var cuotienglishwords = "";
        var cuotitotalenglish = 0;
        cuoti.forEach(element => {
            cuotienglishwords += "." + element.title;
            cuotitotalenglish++;
        });
        for (i = 1; i <= cuotitotalenglish; i++) {
            var cuotiword = cuotienglishwords.toString().split('.')[i];
            var cuotiyuyin = http.get("http://dict.youdao.com/dictvoice?audio=" + cuotiword);
            files.writeBytes("/storage/emulated/0/music.mp3", cuotiyuyin.body.bytes());
            media.playMusic("/storage/emulated/0/music.mp3");
            sleep(media.getMusicDuration() + 500);
            media.playMusic("/storage/emulated/0/music.mp3");
            sleep(media.getMusicDuration() + 1000);
        }
    }
    cuotizhuangtai = 0;
}





var ResultIntent = {
    intentCallback: {},
    init: function () {
        activity.getEventEmitter().on("activity_result", (requestCode, resultCode, data) => {
            this.onActivityResult(requestCode, resultCode, data);
        });
    },
    startActivityForResult: function (intent, callback) {
        var i;
        for (i = 0; i < 65536; i++) {
            if (!(i in this.intentCallback)) break;
        }
        if (i >= 65536) {
            toast("启动Intent失败：同时请求的Intent过多");
            return;
        }
        this.intentCallback[i] = callback;
        activity.startActivityForResult(intent, i);
    },
    onActivityResult: function (requestCode, resultCode, data) {
        var cb = this.intentCallback[requestCode];
        if (!cb) return;
        delete this.intentCallback[requestCode];
        cb(resultCode, data);
    }
};
ResultIntent.init();
function startChooseFile(mimeType, callback) {
    var i = new android.content.Intent(android.content.Intent.ACTION_GET_CONTENT);
    i.setType(mimeType);
    ResultIntent.startActivityForResult(i, function (resultCode, data) {
        if (resultCode != activity.RESULT_OK) return;
        var f = URIUtils_uriToFile(data.getData());
        ui.run(() => {
            ui.text_test.setText(f);
        });
    });
}
function URIUtils_uriToFile(uri) { //Source : https://www.cnblogs.com/panhouye/archive/2017/04/23/6751710.html
    var r = null,
        cursor, column_index, selection = null,
        selectionArgs = null,
        isKitKat = android.os.Build.VERSION.SDK_INT >= 19,
        docs;
    if (uri.getScheme().equalsIgnoreCase("content")) {
        if (isKitKat && android.provider.DocumentsContract.isDocumentUri(activity, uri)) {
            if (String(uri.getAuthority()) == "com.android.externalstorage.documents") {
                docs = String(android.provider.DocumentsContract.getDocumentId(uri)).split(":");
                if (docs[0] == "primary") {
                    return android.os.Environment.getExternalStorageDirectory() + "/" + docs[1];
                }
            } else if (String(uri.getAuthority()) == "com.android.providers.downloads.documents") {
                uri = android.content.ContentUris.withAppendedId(
                    android.net.Uri.parse("content://downloads/public_downloads"),
                    parseInt(android.provider.DocumentsContract.getDocumentId(uri))
                );
            } else if (String(uri.getAuthority()) == "com.android.providers.media.documents") {
                docs = String(android.provider.DocumentsContract.getDocumentId(uri)).split(":");
                if (docs[0] == "image") {
                    uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if (docs[0] == "video") {
                    uri = android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if (docs[0] == "audio") {
                    uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                selection = "_id=?";
                selectionArgs = [docs[1]];
            }
        }
        try {
            cursor = activity.getContentResolver().query(uri, ["_data"], selection, selectionArgs, null);
            if (cursor && cursor.moveToFirst()) {
                r = String(cursor.getString(cursor.getColumnIndexOrThrow("_data")));
            }
        } catch (e) {
            log(e)
        }
        if (cursor) cursor.close();
        return r;
    } else if (uri.getScheme().equalsIgnoreCase("file")) {
        return String(uri.getPath());
    }
    return null;
}